<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="策略名称" prop="strategyNm">
        <el-input
          v-model="queryParams.strategyNm"
          placeholder="请输入策略名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:strategy:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:strategy:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-video-pause"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:strategy:remove']"
        >停止</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:strategy:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="strategyList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />

      <el-table-column label="策略名称" align="center" prop="strategyNm" />
      <el-table-column label="创建者" align="center" prop="creatorNm" />

      <el-table-column label="启用" align="center" prop="isInvalid">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.isInvalid"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTm" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTm, '{yy}-{m}-{dd}') }}</span>
          <!--<span>{{ scope.row.createTm}}</span>-->
        </template>
      </el-table-column>
      <el-table-column label="执行情况" align="center" prop="createTm" width="180">
        <template slot-scope="scope" >
          <!--<span v-if="scope.row.creatorId==null"><font color="#a9a9a9">没有执行</font></span>-->
          <!--<span v-else-if="scope.row.creatorId=='-1'"><font color="#FF0000">执行出错</font></span>-->
          <!--<span v-else-if="scope.row.creatorId=='0'"><font color="#ff1493">准备执行</font></span>-->
          <span v-if="scope.row.creatorId==null"> <el-tag :key="没有执行" type="info" effect="plain"> 没有执行 </el-tag></span>
          <span v-else-if="scope.row.creatorId=='-1'"><el-tag :key="执行出错" type="danger" effect="plain"> 执行出错 </el-tag></span>
          <span v-else-if="scope.row.creatorId=='0'"><el-tag :key="准备执行" type="warning" effect="plain"> 准备执行 </el-tag></span>
          <!--<span v-else-if="scope.row.creatorId=='1'"><font color="green">正在执行</font></span>-->
          <span v-else-if="scope.row.creatorId=='1'"><el-progress :text-inside="true" :stroke-width="15" :percentage="scope.row.strategyLogic"></el-progress></span>
          <span v-else="scope.row.creatorId=='2'"><el-tag :key="执行完成" type="success" effect="plain"> 执行完成 </el-tag></span>
        </template>
      </el-table-column>
      <el-table-column label="执行信息" align="center" prop="applyBoard"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="scope.row.creatorId!='0'&& scope.row.creatorId!='1'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:strategy:edit']"
          > 修改 </el-button>
          <el-button v-if="scope.row.creatorId=='1'"
            size="mini"
            type="text"
            icon="el-icon-video-pause"

            @click="handleDelete(scope.row)"
            v-hasPermi="['system:strategy:remove']"
          >停止</el-button>
          <el-button v-if="scope.row.creatorId!='0'&& scope.row.creatorId!='1'"
            size="mini"
            type="text"
            icon="el-icon-video-play"
            @click="handleExecute(scope.row)"
            v-hasPermi="['system:strategy:edit']"
          >执行</el-button>
          <el-button v-if="scope.row.creatorId=='2' && scope.row.applyBoard!=''"
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="exportOne(scope.row)"
            v-hasPermi="['system:strategy:edit']"
          >导出结果</el-button>
          <el-button v-if="scope.row.creatorId=='2' && scope.row.applyBoard!=''"
                     size="mini"
                     type="text"
                     icon="el-icon-s-data"
                     @click="doShowLog(scope.row)"
                     v-hasPermi="['system:strategy:edit']"
          >分析</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <div v-if="showLog">
      <el-dialog title="分析结果" :visible="showLog" width="1200px" :before-close="doCloseLog">
        <lamlog :query="queryLog" />
      </el-dialog>
    </div>
    <!-- 添加执行的时间范围 -->
    <el-dialog :title="title" :visible.sync="open" width="400px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="form.dateRange"
            size="small"
            style="width: 240px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { Notification, MessageBox, Message, Loading } from 'element-ui'
import { listStrategy,importOne, getStrategy, delStrategy, addStrategy, updateStrategy,ExecutePython } from "@/api/system/strategy";
import lamlog from './analyse';
export default {
  name: "Strategy",
  dicts: ['sys_yes_no'],
  components: { lamlog },
  data() {
    return {
      //参数对象
      queryLog:{
        strategyCd: ''
      },
      showLog:false,
      //刷新操作
      polling: null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 日期范围
      dateRange: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 策略生成表格数据
      strategyList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        strategyNm: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  activated () {
    this.getList();
  },
  created() {
    this.getList();

  },
  mounted(){		//模板渲染之后调用的，模板渲染之前是created
    //刚进页面就能获取到findDB()中的数据
    this.getList();
    this.times()	//加载定时任务
  },
  beforeDestroy () {
    clearInterval(this.times())
  },

  methods: {
    doCloseLog() {
      this.showLog = false;
    },
    doShowLog(item) {
      this.showLog = true;
      this.queryLog.strategyCd = item.strategyCd || this.ids;
      // alert(this.queryLog.strategyCd);
      // this.queryLog.jobId = item.jobId;
    },
    /** 查询策略生成列表 */
    getList() {
      this.loading = true;
      listStrategy(this.queryParams).then(response => {
        this.strategyList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
// 定时按钮
    times(){			//定义了一个times()方法来执行定时查询findDB()
      return setInterval(()=>{			//setInterval换个名字就行了
        this.getList();
      },30000)		//设置时间，这里是1分钟
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        strategyNm: null,
        strategyCd: null,
        creatorNm: null,
        creatorId: null,
        isInvalid: null,
        createTm: null,
        dateRange:[],
        strategyLogic: null,
        strategyContent: null,

        applyBoard: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.strategyCd);
      this.single = selection.length!==1;
      this.multiple = !selection.length
    },
    methodThatForcesUpdate(){
      // alert(1111);
      this.$forceUpdate();
    },
    /** 新增按钮操作 */
    handleAdd() {
      // this.reset();
      // this.open = true;
      // this.title = "添加策略生成";
      // alert(1111);
      // var title = '新增策略';
      var url = '/strategy/category';
      // alert(url);
      this.$router.push(url);
      },
    /** 修改按钮操作 */
    handleUpdate(row) {
      var url = '/strategy/category';
      const strategyCd = row.strategyCd || this.ids;
      // alert(url);
      this.$router.push({path:url,query:{strategyCd:strategyCd}});


    },
    /** 执行按钮操作 */
    handleExecute(row) {
      if(row.creatorId=="-1")
        return this.$modal.msgError(row.applyBoard);
      const strategyCd = row.strategyCd || this.ids;
      this.reset();
      // form.dateRange=[];
      // alert(this.form.dateRange);
      this.form.strategyCd=strategyCd;
      this.open = true;
      this.title = "选择时间范围";
      // alert(strategyCd);
      // ExecutePython(strategyCd).then(response => {
      //   if(response.code==200){
      //     this.$modal.msgSuccess(response.msg);
      //     this.open = false;
      //     this.getList();
      //   }else {
      //     this.$modal.msgError("执行失败！");
      //   }
      // });

    },
    /** 提交按钮 */
    submitForm() {
      // alert(this.form.strategyCd);
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.strategyCd != null) {
            // alert(this.form.dateRange);
            ExecutePython(this.form.strategyCd,this.form.dateRange).then(response => {
              if(response.code==200){
                this.$modal.msgSuccess(response.msg);
                this.open = false;
                this.getList();
              }else {
                this.$modal.msgError("执行失败！");
              }
            });
          } else {
            this.$modal.msgSuccess("系统错误，请联系管理员");
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const strategyCds = row.strategyCd || this.ids;
      this.$modal.confirm('是否确认停止策略生成编号为"' + strategyCds + '"的后台计算？').then(function() {
        return delStrategy(strategyCds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("停止成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/strategy/export', {
        ...this.queryParams
      }, `strategy_${new Date().getTime()}.xlsx`)
    },
    /** 导出数据操作 */
    exportOne(row) {
      // // alert(row.strategyCd);
      // this.download('system/strategy/exportOne/',{
      //     ...row.strategyCd
      //   },
      //  `strategy_${new Date().getTime()}.xlsm`)
      // let downloadLoadingInstance1 = Loading.service({ text: "正在下载数据，请稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })
      const url = '/system/strategy/exportOne/' + row.strategyCd+"_"+new Date().getTime();
      const name = `strategy_${new Date().getTime()}.xlsm`;
      this.$download.download_new_str(url,name);
      // downloadLoadingInstance1.close();
    },
    importOne(row) {
     const url = '/system/strategy/importData/' + row.strategyCd;
      importOne(url).then(response => {
        if(response.code==200){
          this.strategyList = response.rows;
          this.total = response.total;
          this.loading = false;
        }else {
          this.$modal.msgError("系统出错,请联系管理员！");
        }
      });
    }



  }
};
</script>
